package com.coolw.file.controller;

import com.coolw.common.api.BaseResult;
import com.coolw.file.util.FileUtil;
import org.dromara.hutool.http.client.HttpDownloader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件请求控制层
 *
 * @author coolw
 * @date 2022/11/1 15:39
 */
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public BaseResult<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return BaseResult.fail("上传失败，未选择文件");
        }
        FileUtil.upload(file);
        return BaseResult.success();
    }

    /**
     * 文件批量上传
     */
    @PostMapping("/uploadBatch")
    public BaseResult<String> uploadBatch(List<MultipartFile> files) {
        if (files.isEmpty()) {
            return BaseResult.fail("文件为空");
        }
        FileUtil.batchUpload(files);
        return BaseResult.success();
    }

    /**
     * 下载文件,zip格式
     */
    @GetMapping("/downZip")
    public BaseResult<Void> downFileZip(HttpServletResponse response) throws IOException {
        FileUtil.downFileZip(response);
        return BaseResult.success();
    }

    /**
     * 下载文件,zip格式
     */
    @GetMapping("/downZip1")
    public BaseResult<Void> downZip1(HttpServletResponse response) throws IOException {
        FileUtil.downFileZip1(response);
        return BaseResult.success();
    }

    /**
     * 文件预览
     */
    @GetMapping("/preview")
    public void preview(@RequestParam String fileUrl,
                        @RequestParam String fileName,
                        HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Type", "text/html;charset=utf-8");

        HttpDownloader.of(fileUrl).download(response.getOutputStream(), true);
    }
}
